package com.winit.openapi.ums.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.commnad.user.IsExistsEmailCommand;
import com.winit.ums.spi.commnad.user.QueryAccountByCompanyIdAndTypeCommand;
import com.winit.ums.spi.common.CustomerConstant;
import com.winit.ums.spi.common.EnumConstant;
import com.winit.ums.spi.customer.CustomerUsService;
import com.winit.ums.spi.customer.RegisterTemporaryService;
import com.winit.ums.spi.customer.command.ActivationCustomerStatusCommand;
import com.winit.ums.spi.customer.command.IsSigningContractCommand;
import com.winit.ums.spi.customer.command.RegisterUsCustomerCommand;
import com.winit.ums.spi.customer.command.SigningContractCommand;
import com.winit.ums.spi.customer.command.SupplementUsCustomerCommand;
import com.winit.ums.spi.customer.command.UpdatePassWordCommand;
import com.winit.ums.spi.user.command.UpdateLastLoginTimeCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;
import com.winit.ums.spi.vo.CustomerUsVo;
import com.winit.ums.spi.vo.user.UserVO;

/**
 * 美国卖家Controller
 * @author qibin.tang
 *
 */
@Controller
@RequestMapping(value = "/ums/customer")
public class CustomerUsController extends BaseController {
	
	 //状态：初始化
	 private static final String INIT_STATUS="init";
	 //3：接口注册  1：网站注册  2：手动添加
	 private static final String DATA_SOURCE="3";
	 //userName
	 private static final String USER_NAME="userName";
	 private static final long ORGANIZATION_ID_VALUE=1000088L;
	 private static final String SIGNERS="signers";
	
	 @Resource
	 private CustomerUsService customerUsService;
	 
	 @Resource
	 private UmsUserService     umsUserService;
	 
	 @Resource
	 private UmsCustomerService umsCustomerService;
	 
	 @Resource
	 private RegisterTemporaryService registerTemporaryService;
	 
	 
	 /**
     * 修改UMS用户密码
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/updatePassWord")
    public String updatePassWord(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
    	UpdatePassWordCommand command= new UpdatePassWordCommand();
    	if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName").trim());
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, USER_NAME);
        }
        if (json.containsKey("passWord")) {
        	command.setPassWord(json.getString("passWord"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "passWord");
        }
    	command.setCtx(CommandContext.getContext());
        customerUsService.updatePassWord(command);
        return SUCCESS;
    }
	
   
    
	/**
     * 客户注册接口
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/registerUsCustomer")
    public String registerUsCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	//RegisterUsCustomerCommand command = JSON.parseObject(requestMsg.getData().toString(), RegisterUsCustomerCommand.class);
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        RegisterUsCustomerCommand command= new RegisterUsCustomerCommand();
    	if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, USER_NAME);
        }
        if (json.containsKey("country")) {
        	command.setCountry(json.getString("country"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "country");
        }
        command.setCtx(CommandContext.getContext());
		customerUsService.registerUsCustomer(command);
        return SUCCESS;
    }
    
    
    
    /**
     * 卖家登陆时检测 卖家账号是否激活
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/isActivationCustomer")
    public String activationCustomerStatus(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	//ActivationCustomerStatusCommand command = JSON.parseObject(requestMsg.getData().toString(), ActivationCustomerStatusCommand.class);
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
    	ActivationCustomerStatusCommand command= new ActivationCustomerStatusCommand();
    	IsExistsEmailCommand isExistsEmailCommand = new IsExistsEmailCommand();
    	if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName"));
            isExistsEmailCommand.setEmail(json.getString("userName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, USER_NAME);
        }
        if (json.containsKey("passWord")) {
        	command.setPassWord(json.getString("passWord"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "passWord");
        }
    	command.setCtx(CommandContext.getContext());
    	 boolean isActivation=true; //是否激活
         boolean isUsaUser=true;//是否US组织用户
         boolean isRegister=false;
         Map<String, Boolean> returnMapDate = new HashMap<String, Boolean>();
    	//验证账号是否不存在
        Map<String,String> checkMap = umsUserService.checkEmail(isExistsEmailCommand);
        String ums = checkMap.get("user");
        String erp =  checkMap.get("erp");
        String register = checkMap.get("register");
    	if(!"true".equals(ums)&&!"true".equals(erp)&&!"true".equals(register)){
    		throw new ApiException(ErrorCode.USERNAME_NOT_EXIST_ERROR);
    	}
    	if("true".equals(register) && (!"true".equals(ums)&&!"true".equals(erp))){
    		boolean flag = registerTemporaryService.checkUser(command);
    		if(!flag){    			
    			throw new ApiException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
    		//跳转到填写资料页面
    		}else{
    		    isRegister=true;
    		}
    		returnMapDate.put("isRegister", isRegister);
			responseMsg.setData(returnMapDate);
    	}else{
    		CustomerUsVo customerUsVo = customerUsService.queryUser(command);
            //验证账号与密码输入是否有误
    		if (customerUsVo.getUserName() == null) {
    			throw new ApiException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
    		} else {
    			if (!DATA_SOURCE.equals(customerUsVo.getDataSource()) || 
    					customerUsVo.getOrganizationId() == null || 
    					ORGANIZATION_ID_VALUE != customerUsVo.getOrganizationId().longValue()) {
    				//账号未激活，提示用户
    				if (INIT_STATUS.toUpperCase().equals(customerUsVo.getStatus())) {
    					throw new ApiException(ErrorCode.CUSTOMER_NOT_ACTIVE_ERROR);
    				}
    				// 不是通过接口注册的用户
    				isUsaUser = false;
    			}
    			if (INIT_STATUS.equals(customerUsVo.getStatus())) {
    				isActivation = false;
    			}
    		}
            returnMapDate.put("isActivation", isActivation);
            returnMapDate.put("isUsaUser", isUsaUser);
            responseMsg.setData(returnMapDate);
            
            //子账号登录时，系统除了校验子账号的信息、权限之外，还需检测主账号状态是否为“active”，如果是，才可以正常登录。否则，登录失败
            if(CustomerConstant.UmsUserType.CHILD.getVal().equals(customerUsVo.getType())){
            	QueryAccountByCompanyIdAndTypeCommand com = new QueryAccountByCompanyIdAndTypeCommand();
            	com.setCompanyId(customerUsVo.getCompanyId());
            	com.setType(CustomerConstant.UmsUserType.MAIN.getVal());
            	UserVO userVO = umsUserService.queryAccountByCompanyIdAndType(com);
            	                
            	if(userVO != null){
            		if(!EnumConstant.UserStatus.ACTIVE.toString().equalsIgnoreCase(userVO.getStatus())){
            			throw new ApiException(ErrorCode.MAIN_ACCOUNT_STATUS_ERROR);
            		}
            	}
            }
                      
    	}
    	//记录最后登陆时间
    	UpdateLastLoginTimeCommand updateLastLoginTimeCommand = new UpdateLastLoginTimeCommand();
    	updateLastLoginTimeCommand.setUserName(isExistsEmailCommand.getEmail());
    	umsUserService.updateLastLoginTime(updateLastLoginTimeCommand);
        return SUCCESS;
    }
    
    
    
    /**
     * 卖家登陆时检测 卖家账号是否激活
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/isActivationforScan")
    public String isActivationforScan(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        //ActivationCustomerStatusCommand command = JSON.parseObject(requestMsg.getData().toString(), ActivationCustomerStatusCommand.class);
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ActivationCustomerStatusCommand command= new ActivationCustomerStatusCommand();
        IsExistsEmailCommand isExistsEmailCommand = new IsExistsEmailCommand();
        if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName"));
            isExistsEmailCommand.setEmail(json.getString("userName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, USER_NAME);
        }
        if (json.containsKey("passWord")) {
            command.setPassWord(json.getString("passWord"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "passWord");
        }
        command.setCtx(CommandContext.getContext());
         boolean isActivation=true; //是否激活
         boolean isUsaUser=true;//是否US组织用户
         boolean isRegister=false;
         Map<String, Object> returnMapDate = new HashMap<String, Object>();
        //验证账号是否不存在
        Map<String,String> checkMap = umsUserService.checkEmail(isExistsEmailCommand);
        String ums = checkMap.get("user");
        String erp =  checkMap.get("erp");
        String register = checkMap.get("register");
        if(!"true".equals(ums)&&!"true".equals(erp)&&!"true".equals(register)){
            throw new ApiException(ErrorCode.USERNAME_NOT_EXIST_ERROR);
        }
        if("true".equals(register) && (!"true".equals(ums)&&!"true".equals(erp))){
            boolean flag = registerTemporaryService.checkUser(command);
            if(!flag){              
                throw new ApiException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
            //跳转到填写资料页面
            }else{
                isRegister=true;
            }
            returnMapDate.put("isRegister", isRegister);
        }else{
            CustomerUsVo customerUsVo = customerUsService.queryUser(command);
            //验证账号与密码输入是否有误
            if (customerUsVo.getUserName() == null) {
                throw new ApiException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
            } else {
                if (!DATA_SOURCE.equals(customerUsVo.getDataSource()) || 
                        customerUsVo.getOrganizationId() == null || 
                        ORGANIZATION_ID_VALUE != customerUsVo.getOrganizationId().longValue()) {
                    //账号未激活，提示用户
                    if (INIT_STATUS.toUpperCase().equals(customerUsVo.getStatus())) {
                        throw new ApiException(ErrorCode.CUSTOMER_NOT_ACTIVE_ERROR);
                    }
                    // 不是通过接口注册的用户
                    isUsaUser = false;
                }
                if (INIT_STATUS.equals(customerUsVo.getStatus())) {
                    isActivation = false;
                }
            }
            returnMapDate.put("isActivation", isActivation);
            returnMapDate.put("isUsaUser", isUsaUser);
            
            
            //子账号登录时，系统除了校验子账号的信息、权限之外，还需检测主账号状态是否为“active”，如果是，才可以正常登录。否则，登录失败
            if(CustomerConstant.UmsUserType.CHILD.getVal().equals(customerUsVo.getType())){
                QueryAccountByCompanyIdAndTypeCommand com = new QueryAccountByCompanyIdAndTypeCommand();
                com.setCompanyId(customerUsVo.getCompanyId());
                com.setType(CustomerConstant.UmsUserType.MAIN.getVal());
                UserVO userVO = umsUserService.queryAccountByCompanyIdAndType(com);
                                
                if(userVO != null){
                    if(!EnumConstant.UserStatus.ACTIVE.toString().equalsIgnoreCase(userVO.getStatus())){
                        throw new ApiException(ErrorCode.MAIN_ACCOUNT_STATUS_ERROR);
                    }
                }
            }
                      
        }
        
        GetByKeyCommand<String> byKeyCommand = new GetByKeyCommand<String>();
        byKeyCommand.setSearchKey(command.getUserName());
        UserVO userVO = umsUserService.queryByUsername(byKeyCommand);

                
        GetByKeyCommand<Long> mixCommand = new GetByKeyCommand<Long>();
        mixCommand.setSearchKey(userVO.getCompanyId());         
       CustomerInfoVO customerInfoVO = umsCustomerService.queryMixCompanyById(mixCommand);
       customerInfoVO.setUsername(userVO.getUsername());
       customerInfoVO.setRealName(userVO.getRealName());
       
       returnMapDate.put("customerInfoVO", customerInfoVO);
       responseMsg.setData(returnMapDate);
        return SUCCESS;
    }
     
    /**
     * 美国卖家签订winit头程代理合同
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/signingContract")
    public String signingContract(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	//SigningContractCommand command = JSON.parseObject(requestMsg.getData().toString(), SigningContractCommand.class);
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
    	SigningContractCommand command= new SigningContractCommand();
    	if (json.containsKey("signers")) {
            command.setSigners(json.getString("signers"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, SIGNERS);
        }
        /*if (json.containsKey("organizationId")) {
        	command.setOrganizationId(json.getInteger("organizationId"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, ORGANIZATION_ID);
        }*/
        command.setCtx(CommandContext.getContext());
        customerUsService.signingContract(command);
        return SUCCESS;
    }
    
    /**
     * 验证美国卖家是否签订头程合同
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/isSigningContract")
    public String isSigningContract (@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	//IsSigningContractCommand command = JSON.parseObject(requestMsg.getData().toString(), IsSigningContractCommand.class);
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
    	IsSigningContractCommand command= new IsSigningContractCommand();
    	if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, USER_NAME);
        }
        /*if (json.containsKey("organizationId")) {
        	command.setOrganizationId(json.getInteger("organizationId"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, ORGANIZATION_ID);
        }*/
    	command.setCtx(CommandContext.getContext());
        boolean bool=customerUsService.isSigningContract(command);
        Map<String, Boolean> returnMapDate = new HashMap<String, Boolean>();
        returnMapDate.put("isSigningContract", bool);
        responseMsg.setData(returnMapDate);
        return SUCCESS;
    }
    
    /**
     * 补填美国卖家注册信息
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/supplementUsCustomer")
    public String supplementUsCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	//SupplementUsCustomerCommand command = JSON.parseObject(requestMsg.getData().toString(), SupplementUsCustomerCommand.class);
    	JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
    	SupplementUsCustomerCommand command = new SupplementUsCustomerCommand();
    	if (json.containsKey("userName")) {
            command.setUserName(json.getString("userName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "userName");
        }
    	if (json.containsKey("passWord")) {
            command.setPassWord(json.getString("passWord"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "passWord");
        }
    	if (json.containsKey("phone")) {
            command.setPhone(json.getString("phone"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "phone");
        }
    	if (json.containsKey("companyName")) {
            command.setCompanyName(json.getString("companyName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "companyName");
        }
    	if (json.containsKey("firstName")) {
            command.setFirstName(json.getString("firstName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "firstName");
        }
    	if (json.containsKey("lastName")) {
            command.setLastName(json.getString("lastName"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "lastName");
        }
    	if (json.containsKey("address")) {
            command.setAddress(json.getString("address"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "address");
        }
    	if (json.containsKey("address1")) {
            command.setAddress1(json.getString("address1"));
        }/*else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "address1");
        }*/
    	if (json.containsKey("address2")) {
            command.setAddress2(json.getString("address2"));
        }/*else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "address2");
        }*/
    	if (json.containsKey("city")) {
            command.setCity(json.getString("city"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "city");
        }
    	if (json.containsKey("state")) {
            command.setState(json.getString("state"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "state");
        }
    	if (json.containsKey("zipCode")) {
            command.setZipCode(json.getString("zipCode"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "zipCode");
        }
    	if (json.containsKey("customerServicePhone")) {
            command.setCustomerServicePhone(json.getString("customerServicePhone"));
        }/*else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "customerServicePhone");
        }*/
    	if (json.containsKey("customerServiceEmail")) {
            command.setCustomerServiceEmail(json.getString("customerServiceEmail"));
        }/*else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "customerServiceEmail");
        }*/
    	if (json.containsKey("ein")) {
            command.setEin(json.getString("ein"));
        }else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "ein");
        }	
    	command.setCtx(CommandContext.getContext());
    	customerUsService.supplementUsCustomer(command);
    	return SUCCESS;
    }
     
}
